package com.lelefly.base.serviceImp;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.service.spi.ServiceException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.lelefly.base.daoimp.BaseDao;
import com.lelefly.base.daoimp.UavInfoDao;
import com.lelefly.base.model.ActivatePlaneBean;
import com.lelefly.base.model.PlaneDetailBean;
import com.lelefly.base.model.RequestAreaBean;
import com.lelefly.base.model.RequestPlaneDetailBean;
import com.lelefly.base.model.Result;
import com.lelefly.base.model.RowResult;
import com.lelefly.base.model.SyncPlaneTimeBean;
import com.lelefly.base.model.UavTimeBean;
import com.lelefly.base.po.LeleflyOrganization;
import com.lelefly.base.po.RegInfo;
import com.lelefly.base.po.UavDistributor;
import com.lelefly.base.po.UavDistributorInfo;
import com.lelefly.base.po.UavInfo;
import com.lelefly.base.po.UavInfoNew;
import com.lelefly.base.po.UavTime;
import com.lelefly.base.utils.DateUtils;
import com.lelefly.constant.Constant;
import com.lelefly.handleexecption.ServiceExecption;
import com.lelefly.handleexecption.ValidateExecption;

@Service
public class UavInfoService {

	@Resource
	public BaseDao baseDao;

	@Resource
	public UavInfoDao uavInfoDao;
	@Resource
	private JdbcTemplate jdbcTemplate;

	@SuppressWarnings({ "null", "rawtypes" })
	public Result getUavInfo(String uavHaver) {
		Result<UavInfo> result = new Result<>();
		try {
			if (StringUtils.isEmpty(uavHaver)) {
				throw new ServiceExecption("参数错误");
			}
			String hql = "from UavInfo as model where uavHaver='" + uavHaver
					+ "' ";
			List<UavInfo> uavInfos = baseDao.queryObjetReList(hql);
			result.setState(Constant.HTTP_STATUS_OK);
			result.setResultList(uavInfos);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	@SuppressWarnings({ "null", "rawtypes" })
	public Result addUavInfo(UavInfo uavInfo) {
		Result<UavInfo> result = new Result<>();
		try {
			String sql = "from UavInfo as model where uavnm ='"
					+ uavInfo.getId() + "'";
			UavInfo uavInfo2 = (UavInfo) baseDao.getObjcetReUnique(sql);
			if (uavInfo2 != null) {
				throw new ValidateExecption("该无人机已经存在");
			}
			baseDao.saveObject(uavInfo);
			result.setState(Constant.HTTP_STATUS_OK);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ValidateExecption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	@SuppressWarnings({ "null", "rawtypes" })
	public Result updateUavInfo(UavInfo uavInfo) {
		Result<UavInfo> result = new Result<>();
		try {
			baseDao.UpdateObject(uavInfo);
			result.setState(Constant.HTTP_STATUS_OK);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		}
		return result;
	}

	@SuppressWarnings("null")
	public Result delUavInfo(String uavnm) {
		Result<UavInfo> result = new Result<>();
		try {
			if (StringUtils.isEmpty(uavnm)) {
				throw new ServiceExecption("删除条件为空");
			}
			String sql = "delete UavInfo as model where uavnm='" + uavnm + "' ";
			baseDao.deteleObjectbySql(sql);
			result.setState(Constant.HTTP_STATUS_OK);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(Constant.HTTP_STATUS_DEFERROR);
		} catch (ServiceExecption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMessage());
		}
		return result;
	}

	/**
	 * 激活飞机
	 * 
	 * @param planeBean
	 * @return
	 */
	public Result activatePlane(ActivatePlaneBean planeBean) {
		Result result = new Result<>();
		
		try {
			/***********   验证码是否正确开始  **************/
			String hql = "from RegInfo as mdoel where tel='"
					+ planeBean.getDistributorPhoneNo() + "' and mesType='"
					+ Constant.CODE_TYPE_ACTIVE_MES + "'";
			RegInfo regInfo = (RegInfo) baseDao.getObjcetReUnique(hql);
			if (regInfo == null) {
				throw new ServiceExecption("验证码不正确");
			}else {
				// 判断验证码是否过期
				if ((System.currentTimeMillis() - Long.valueOf(regInfo.getExpiredTime())) > 1000 * 60 * 30) {
					throw new ServiceException("验证码已过期，请重新获取");
				}
			}
			/***********   验证码是否正确结束  **************/
			
			
			String hasPlaneSql = "from UavInfoNew where uavid='"
					+ planeBean.getPlaneId() + "'";
			UavInfoNew hasPlaneInfoNew = (UavInfoNew) baseDao
					.getObjcetReUnique(hasPlaneSql);
			if (hasPlaneInfoNew != null) {
				throw new ServiceException("当前飞机已被激活，请勿重复激活！");
			}

			String validateSql = "from UavInfoNew where uavHaver='"
					+ planeBean.getUavActivater() + "' and planeName='"
					+ planeBean.getPlaneName() + "'";

			UavInfoNew uavInfo = (UavInfoNew) baseDao
					.getObjcetReUnique(validateSql);
			if (uavInfo != null) {
				throw new ServiceException("当前名称已占用");
			}

			UavInfoNew uavInfoNew = new UavInfoNew();
			uavInfoNew.setAtiveTime(DateUtils.getCurDate());
			uavInfoNew.setIsCased("0");
			uavInfoNew.setLastCount("0");
			uavInfoNew.setUavHavaer(planeBean.getUavActivater());
			uavInfoNew.setUavHaver(planeBean.getUavActivater());
			uavInfoNew.setUavid(planeBean.getUavid());
			uavInfoNew.setUavname(planeBean.getUavName());
			uavInfoNew.setUavVersion(planeBean.getUavVersion());
			uavInfoNew.setUserphone(planeBean.getUavActivater());
			uavInfoNew.setPlaneName(planeBean.getPlaneName());
			uavInfoNew.setAgencyphone(planeBean.getDistributorPhoneNo());

			baseDao.saveObject(uavInfoNew);
			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes("激活成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("激活失败，请重新激活");
		} catch (ServiceExecption e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(e.getMes());
		}
		return result;
	}

	public Result<UavInfoNew> getMyPlane(String phoneNo) {
		Result<UavInfoNew> result = new Result<>();
		try {
			String hql = "from UavInfoNew as model where uavHaver='" + phoneNo
					+ "'";
			List<UavInfoNew> list = baseDao.queryObjetReList(hql);
			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes("查询成功");
			result.setResultList(list);
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("服务器内部错误！");
		}

		return result;
	}

	public Result<PlaneDetailBean> queryPlaneDetail(RequestPlaneDetailBean bean) {
		Result<PlaneDetailBean> result = new Result<>();
		try {
			String sql = "SELECT SUM(CAST(fly_area AS DECIMAL(10,2))) AS totalFlyArea,"
					+ "TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(fly_end_time,fly_begin_time)))),'%H:%i:%s') AS totalFlyTime "
					+ "FROM lelefly_history_info WHERE plane_id='"
					+ bean.getPlaneId() + "'";
			List<PlaneDetailBean> resultList = uavInfoDao.queryPlaneDetail(sql);
			String hql = "from LeleflyOrganization as model where organizationOwner='"
					+ bean.getPhoneNo() + "'";
			LeleflyOrganization organization = (LeleflyOrganization) baseDao
					.getObjcetReUnique(hql);
			if (resultList != null && resultList.size() > 0) {
				if (organization != null) {
					resultList.get(0).setOrgnizationName(
							organization.getOrganizationName());
				}
			}
			result.setResultList(resultList);
			result.setMes("查询成功");
			result.setState(Constant.HTTP_STATUS_OK);

		} catch (Exception e) {
			e.printStackTrace();
			result.setMes("服务器内部错误");
			result.setState(Constant.HTTP_STATUS_FAIL);
		}

		return result;
	}

	public Result<BigDecimal> queryFlyArea(RequestAreaBean bean) {
		Result<BigDecimal> result = new Result<>();
		try {
			String sql = "select sum(CAST(fly_area AS DECIMAL(10,2))) from lelefly_history_info "
					+ "where fly_begin_time>'"
					+ bean.getBeginTime()
					+ "' and fly_end_time<'"
					+ bean.getEndTime()
					+ "'"
					+ " and plane_id='" + bean.getPlaneId() + "'";
			BigDecimal area = (BigDecimal) uavInfoDao
					.getObjcetReUniqueBySql(sql);
			List<BigDecimal> list = new ArrayList<>();
			if (area == null) {
				list.add(new BigDecimal("0.0"));
			} else {
				list.add(area);
			}
			result.setResultList(list);
			result.setMes("查询成功");
			result.setState(Constant.HTTP_STATUS_OK);

		} catch (Exception e) {
			e.printStackTrace();
			result.setMes("服务器内部错误");
			result.setState(Constant.HTTP_STATUS_FAIL);
		}
		return result;
	}

	public Result updateLeftTime(UavTimeBean bean) {
		Result result = new Result<>();
		// 验证用户名和密码是否正确
		int userNo = bean.getUserNo();
		String pwd = bean.getPassword();
		String planeId = bean.getUavId();

		try {
			String validatePwdSql = "from UavDistributor where distributorNo= "
					+ userNo + " and " + "distributorPwd='" + pwd + "'";
			UavDistributor distributor = (UavDistributor) baseDao
					.getObjcetReUnique(validatePwdSql);
			if (distributor == null) {
				throw new ServiceException("用户名或密码不正确");
			}
			// 查询经销商账号下是否有该飞机
			String uavInfoHql = "from UavDistributorInfo where planeId='"
					+ planeId + "'" + " and distributorNo='" + userNo + "'";
			UavDistributorInfo info = (UavDistributorInfo) baseDao
					.getObjcetReUnique(uavInfoHql);
			if (info == null) {
				throw new ServiceException("未查询到飞机");
			}
			// 更新飞行时间
			String uavTimeHql = "from UavTime where uavId='" + planeId + "'";
			UavTime uavTime = (UavTime) baseDao.getObjcetReUnique(uavTimeHql);
			if (uavTime == null) {
				throw new ServiceException("该飞机不存在");
			}
			// 当前剩余的飞行时间
			int leftTime = uavTime.getUavTime();
			uavTime.setUavTime(leftTime + bean.getUavTime());
			baseDao.saveOrUpdateObject(uavTime);
			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes("时间设置成功");

		} catch (ServiceException message) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(message.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("服务器异常,更新失败");
		}
		return result;
	}

	public Result queryUavLeftTime(UavTimeBean bean) {
		Result result = new Result<>();
		// 验证用户名和密码是否正确
		int userNo = bean.getUserNo();
		String pwd = bean.getPassword();
		String planeId = bean.getUavId();

		try {
			String validatePwdSql = "from UavDistributor where distributorNo= "
					+ userNo + " and " + "distributorPwd='" + pwd + "'";
			UavDistributor distributor = (UavDistributor) baseDao
					.getObjcetReUnique(validatePwdSql);
			if (distributor == null) {
				throw new ServiceException("用户名或密码不正确");
			}
			// 查询经销商账号下是否有该飞机
			String uavInfoHql = "from UavDistributorInfo where planeId='"
					+ planeId + "'" + " and distributorNo='" + userNo + "'";
			UavDistributorInfo info = (UavDistributorInfo) baseDao
					.getObjcetReUnique(uavInfoHql);
			if (info == null) {
				throw new ServiceException("未查询到飞机");
			}
			// 更新飞行时间
			String uavTimeHql = "from UavTime where uavId='" + planeId + "'";
			UavTime uavTime = (UavTime) baseDao.getObjcetReUnique(uavTimeHql);
			if (uavTime == null) {
				throw new ServiceException("该飞机不存在");
			}
			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes(uavTime.getUavTime() + "");

		} catch (ServiceException message) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(message.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("服务器异常,更新失败");
		}

		return result;
	}

	public Result<UavTime> syncPlaneTime(SyncPlaneTimeBean bean) {
		Result<UavTime> result = new Result<>();

		String hql = "from UavTime where planeId='" + bean.getUavId() + "'";
		try {
			UavTime info = (UavTime) baseDao.getObjcetReUnique(hql);
			result.setState(Constant.HTTP_STATUS_OK);
			if (info != null) {
				result.setMes("查询成功");

				BigInteger serverTotalTime = info.getUavTotalFlyTime();
				if (serverTotalTime == null) {
					info.setUavTotalFlyTime(new BigInteger("0"));
				}
				int serverLeftTime = info.getUavTime();
				// 总时间差值
				int minusTime = bean.getTotalFlyTime()
						- info.getUavTotalFlyTime().intValue();
				// 更新服务器剩余时间
				int minusUavTime = serverLeftTime - minusTime;
				if (minusTime < 0) {
					info.setUavTime(0);
				}
				info.setUavTime(minusUavTime);
				baseDao.saveObject(info);
				List<UavTime> list = new ArrayList<>();
				list.add(info);
				result.setResultList(list);
			} else {
				result.setMes("没有对应的飞机信息");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("服务器异常,查询失败");
		}
		return result;
	}

	public Result lockUav(UavTimeBean bean) {
		Result result = new Result();
		// 验证用户名和密码是否正确
		int userNo = bean.getUserNo();
		String pwd = bean.getPassword();
		String planeId = bean.getUavId();

		try {
			String validatePwdSql = "from UavDistributor where distributorNo= "
					+ userNo + " and " + "distributorPwd='" + pwd + "'";
			UavDistributor distributor = (UavDistributor) baseDao
					.getObjcetReUnique(validatePwdSql);
			if (distributor == null) {
				throw new ServiceException("用户名或密码不正确");
			}
			// 查询经销商账号下是否有该飞机
			String uavInfoHql = "from UavDistributorInfo where planeId='"
					+ planeId + "'" + " and distributorNo='" + userNo + "'";
			UavDistributorInfo info = (UavDistributorInfo) baseDao
					.getObjcetReUnique(uavInfoHql);
			if (info == null) {
				throw new ServiceException("未查询到飞机");
			}
			// 更新飞行时间
			String uavTimeHql = "from UavTime where uavId='" + planeId + "'";
			UavTime uavTime = (UavTime) baseDao.getObjcetReUnique(uavTimeHql);
			if (uavTime == null) {
				throw new ServiceException("该飞机不存在");
			}
			uavTime.setUavLeftCount(0);
			baseDao.saveOrUpdateObject(uavTime);

			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes("飞机锁定成功");
		} catch (ServiceException message) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes(message.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("服务器异常,更新失败");
		}

		return result;
	}
	
	
	public RowResult<UavInfoNew> getDistributorPlane(String phoneNum,String start,String limit){
		RowResult<UavInfoNew> result = new RowResult<>();
		try {
//			String hql = "from UavInfoNew where agencyphone='" + phoneNum + "'";
			String sql = "SELECT uavid,uav_version,UAV_haver,"
					+ "ative_time,uav_havaer,agency,last_count,"
					+ "isCased,userphone,agencyphone,plane_name,"
					+ "(SELECT username FROM lelefly_user WHERE phonenumber='" + phoneNum + "') "
					+ "UAVname FROM uav_info_new WHERE agencyphone='" + phoneNum + "'";
			List<UavInfoNew> list = baseDao.queryObjetReListBySql(sql, UavInfoNew.class);
			result.setRows(list);
			result.setTotal(list.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
